<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>创建策略 - 币胜客pro</title>
    <link rel="stylesheet" href="styles.css" />
    <style>
      body {
        min-height: 100vh;
        background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
        display: flex;
        align-items: center;
        justify-content: center;
        color: #0f172a;
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
      }
      .page-wrap {
        width: min(520px, 92vw);
        background: #ffffff;
        border-radius: 20px;
        padding: 32px;
        box-shadow: 0 24px 60px rgba(15, 23, 42, 0.25);
        display: flex;
        flex-direction: column;
        gap: 24px;
      }
      .page-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      .page-title {
        margin: 0;
        font-size: 24px;
        font-weight: 700;
        color: #0f172a;
      }
      .page-subtitle {
        margin: 4px 0 0;
        color: #475569;
        font-size: 14px;
      }
      .link-btn {
        border: none;
        background: none;
        color: #0ea5e9;
        cursor: pointer;
        font-size: 14px;
        padding: 4px 8px;
      }
      .form {
        display: flex;
        flex-direction: column;
        gap: 16px;
      }
      .form-footer {
        display: flex;
        justify-content: flex-end;
        gap: 12px;
        margin-top: 8px;
      }
      .btn.secondary {
        background: #e2e8f0;
        color: #1e293b;
      }
      .btn.secondary:hover {
        background: #cbd5f5;
      }
      .result-card {
        background: #f1f5f9;
        border-radius: 12px;
        padding: 16px;
        display: none;
        flex-direction: column;
        gap: 12px;
      }
      .copy-field {
        display: flex;
        gap: 8px;
        align-items: center;
      }
      .copy-field input {
        flex: 1;
      }
      .copy-field button {
        flex: none;
      }
      .muted {
        color: #64748b;
        font-size: 13px;
      }
      @media (max-width: 640px) {
        body { padding: 16px; }
        .page-wrap { padding: 24px; }
        .form-footer { flex-direction: column; }
        .form-footer .btn { width: 100%; }
      }
    </style>
  </head>
  <body>
    <main class="page-wrap" role="main">
      <header class="page-header">
        <div>
          <h1 class="page-title">创建策略</h1>
          <p class="page-subtitle">配置策略基础信息并提交至控制面板</p>
        </div>
        <button class="link-btn" id="btn-go-back">← 返回策略管理</button>
      </header>

      <form class="form" id="create-strategy-form" autocomplete="off">
        <div class="field">
          <label for="strategy-name">策略名称</label>
          <input id="strategy-name" class="input" placeholder="如 趋势跟随" required />
        </div>
        <div class="field">
          <label for="strategy-symbol">交易符号</label>
          <input id="strategy-symbol" class="input" placeholder="如 BTC-USDT" required />
        </div>
        <div class="field">
          <label for="strategy-market">市场类型</label>
          <select id="strategy-market" class="input">
            <option value="spot">现货 (spot)</option>
            <option value="perpetual">合约 (perpetual)</option>
          </select>
        </div>
        <div class="form-msg" id="form-msg" aria-live="polite"></div>
        <div class="form-footer">
          <button class="btn secondary" type="button" id="btn-cancel">取消</button>
          <button class="btn primary" type="submit" id="btn-submit">保存</button>
        </div>
      </form>
    </main>

    <script>
      (function () {
        'use strict';

        var API_BASE = 'http://43.153.150.144:8080';

        function getToken() {
          try { return localStorage.getItem('token') || ''; } catch (_) { return ''; }
        }

        async function request(method, path, body) {
          var headers = { 'Content-Type': 'application/json' };
          var token = getToken();
          if (token) headers.Authorization = 'Bearer ' + token;
          return fetch(API_BASE + path, {
            method: method,
            headers: headers,
            body: body ? JSON.stringify(body) : undefined
          });
        }

        var form = document.getElementById('create-strategy-form');
        var msg = document.getElementById('form-msg');
        var btnSubmit = document.getElementById('btn-submit');
        var btnCancel = document.getElementById('btn-cancel');
        var btnBack = document.getElementById('btn-go-back');
        var redirectTimer = null;

        function setMessage(text, tone) {
          msg.textContent = text || '';
          msg.className = 'form-msg';
          if (tone === 'success') {
            msg.style.color = '#16a34a';
          } else if (tone === 'error') {
            msg.style.color = '#dc2626';
          } else {
            msg.style.color = '#0ea5e9';
          }
        }
        setMessage('', 'info');

        function goBack() {
          if (redirectTimer) {
            clearTimeout(redirectTimer);
            redirectTimer = null;
          }
          if (document.referrer && document.referrer.indexOf('strategy-manager') >= 0) {
            history.back();
          } else {
            window.location.href = 'strategy-manager.html';
          }
        }

        btnBack.addEventListener('click', goBack);
        btnCancel.addEventListener('click', goBack);

        form.addEventListener('submit', async function (ev) {
          ev.preventDefault();
          if (redirectTimer) {
            clearTimeout(redirectTimer);
            redirectTimer = null;
          }
          var name = document.getElementById('strategy-name').value.trim();
          var symbol = document.getElementById('strategy-symbol').value.trim();
          var market = document.getElementById('strategy-market').value || 'spot';

          if (!name || !symbol) {
            setMessage('请完整填写策略名称与交易符号。', 'error');
            return;
          }

          btnSubmit.disabled = true;
          setMessage('提交中...', 'info');

          try {
            var payload = { name: name, symbol: symbol, market_type: market };
            var res = await request('POST', '/scripts', payload);
            var isJson = res.headers && res.headers.get('content-type') && res.headers.get('content-type').indexOf('application/json') >= 0;
            var data = isJson ? await res.json() : await res.text();

            if (!res.ok) {
              throw new Error((data && data.message) || (data && data.detail) || ('HTTP ' + res.status));
            }

            setMessage('策略创建成功，3 秒后返回策略列表...', 'success');
            redirectTimer = setTimeout(function () {
              window.location.href = 'strategy-manager.html';
            }, 3000);
          } catch (err) {
            setMessage('创建失败：' + (err && err.message ? err.message : '未知错误'), 'error');
          } finally {
            btnSubmit.disabled = false;
          }
        });

        window.addEventListener('beforeunload', function () {
          if (redirectTimer) {
            clearTimeout(redirectTimer);
            redirectTimer = null;
          }
        });
      })();
    </script>
  </body>
</html>
